<template>
  <div class="field-assign">
    <je-grid
      ref="grid"
      border
      auto-resize
      show-overflow="ellipsis"
      keep-source
      show-header-overflow
      resizable
      :height="gridHeight"
      size="mini"
      :loading="loading"
      header-align="center"
      :edit-config="{
        trigger: 'click',
        mode: 'cell',
        showUpdateStatus: true,
        showInsertStatus: false,
      }"
      class="field-assign-grid"
      :data="gridData"
      @cell-mouseenter="onMouseenter"
      @cell-mouseleave="onMouseleave"
    >
      <je-column field="name" title="字段名" width="50%">
        <template #default="{ row }">
          <div class="field-assign-grid-column-name">
            <span v-html="formatSearchData(row.name)"> </span>
            <Tooltip placement="topRight" :title="row.code">
              <i type="primary" class="solid fal fa-ellipsis-v"></i>
            </Tooltip>
          </div>
        </template>
      </je-column>
      <je-column
        field="value"
        :title="$t('AssignmentConstructor.value')"
        :edit-render="inputRender"
      >
        <template #edit="{ row }">
          <je-select v-model:value="row.value" :options="JE_WF_DEFAULTVALUE" editable />
        </template>
        <template #default="{ row }">
          {{ getSelectLabel(row.value, JE_WF_DEFAULTVALUE) }}
        </template>
      </je-column>
      <template #tbar>
        <InputSearch
          v-model:value="searchValue"
          class="inputsearch"
          style="height: 32px"
          allow-clear
          placeholder="搜索"
          @search="doSearch"
          ><template #prefix><i class="fal fa-search" /> </template>
        </InputSearch>
      </template>
    </je-grid>
  </div>
</template>

<script>
  import { defineComponent, ref, watch } from 'vue';
  import { Grid, Select, Tooltip, Input } from '@jecloud/ui';
  import { inputRender } from '@/helper/edit-render';
  import { isNotEmpty, cloneDeep } from '@jecloud/utils';
  import { JE_WF_DEFAULTVALUE } from '@/helper/constant';

  export default defineComponent({
    name: 'FieldAssign',
    components: {
      JeGrid: Grid,
      JeColumn: Grid.Column,
      JeSelect: Select,
      Tooltip,
      InputSearch: Input.Search,
    },
    props: {
      fieldDatas: {
        type: Array,
        default: () => {
          return [];
        },
      },
      fieldAssignment: {
        type: Object,
        default: () => {
          return {};
        },
      },
      nodeId: {
        type: String,
        default: '',
      },
      gridHeight: {
        type: Number,
        default: 0,
      },
    },
    emits: ['setConfigData'],
    setup(props, { emit }) {
      const grid = ref(null);
      const gridData = ref([]);
      const loading = ref(true);
      const searchValue = ref('');
      //监听传入的数据给列表赋值
      watch(
        () => props.fieldDatas,
        (newVal) => {
          if (newVal && newVal.length > 0) {
            const data = cloneDeep(newVal);
            //根据主数据回显列表数据
            if (isNotEmpty(props.fieldAssignment)) {
              data.forEach((item) => {
                for (let key in props.fieldAssignment) {
                  if (key == item.code) {
                    item.value = props.fieldAssignment[key];
                  }
                }
              });
            }
            gridData.value = data;
          }
          loading.value = false;
        },
        { deep: true, immediate: true },
      );

      //监听列表数据
      watch(
        () => gridData.value,
        (newVal) => {
          const datas = {};
          newVal.forEach((item) => {
            if (item.value) {
              datas[item.code] = item.value;
            }
          });
          emit('setConfigData', { type: 'fieldAssignment', datas });
        },
        {
          deep: true,
        },
      );

      //监听节点ID刷新表格数据
      watch(
        () => props.nodeId,
        () => {
          if (gridData.value.length > 0 && props.fieldAssignment) {
            searchValue.value = '';
            gridData.value.forEach((item) => {
              if (props.fieldAssignment[item.code]) {
                item.value = props.fieldAssignment[item.code];
              } else {
                item.value = '';
              }
            });
            grid.value.loadData(gridData.value);
          }
        },
      );

      //列表单元格格式化
      const getSelectLabel = (value, list, valueProp = 'value', labelField = 'label') => {
        const item = list.find((item) => item[valueProp] === value);
        return item ? item[labelField] : value;
      };

      // 鼠标移入单元格
      const onMouseenter = ({ cell }) => {
        const solidEl = cell.getElementsByClassName('solid');
        if (solidEl && solidEl.length > 0) {
          solidEl[0].style.display = 'block';
        }
      };

      // 鼠标移出单元格
      const onMouseleave = ({ cell }) => {
        const solidEl = cell.getElementsByClassName('solid');
        if (solidEl && solidEl.length > 0) {
          solidEl[0].style.display = 'none';
        }
      };

      // 搜索
      const doSearch = () => {
        let searchData = [];
        if (isNotEmpty(searchValue.value)) {
          const keyword = searchValue.value.toString().toLocaleLowerCase();
          gridData.value.forEach((item) => {
            if (
              item.code.toString().toLocaleLowerCase().indexOf(keyword) != -1 ||
              item.name.indexOf(keyword) != -1
            ) {
              searchData.push(item);
            }
          });
        } else {
          searchData = gridData.value;
        }
        grid.value.loadData(searchData);
      };

      // 高亮
      const formatSearchData = (name) => {
        let text = name;
        if (isNotEmpty(name) && isNotEmpty(searchValue.value)) {
          var re = new RegExp(searchValue.value, 'g');
          let replaceString = '<span style="color:red;">' + searchValue.value + '</span>';
          text = name.replace(re, replaceString);
        }
        return text;
      };

      return {
        gridData,
        loading,
        grid,
        JE_WF_DEFAULTVALUE,
        getSelectLabel,
        inputRender,
        onMouseenter,
        onMouseleave,
        searchValue,
        doSearch,
        formatSearchData,
      };
    },
  });
</script>

<style lang="less" scoped>
  .field-assign {
    &-grid {
      &-column-name {
        align-items: center;
        display: flex;
        justify-content: space-between;
        .solid {
          cursor: pointer;
          display: none;
          &:hover {
            font-weight: 700;
            color: #3265f5;
          }
        }
      }
      .inputsearch {
        .ant-input-group-addon {
          display: none;
        }
      }
    }
  }
</style>

<style lang="less">
  .field-assign {
    &-grid {
      .inputsearch {
        .ant-input-group-addon {
          display: none;
        }
      }
    }
  }
</style>
